#include <stdio.h>
#include <windows.h>
#include <stdint.h>

// 计算校验和
uint8_t calculate_checksum(uint8_t *data, uint8_t length)
{
    uint8_t checksum = 0;
    for(uint8_t i = 0; i< length; i++)
    {
        checksum ^= data[i];
    }
    return checksum;
}


// 协议解析函数
int parse_protocol(uint8_t *packet, uint8_t packet_length, uint8_t **data, uint8_t *data_length )
{
    // 检查数据包长度是否足够
    if(packet_length < 3)
    {
        return -1; //数据包长度不足
    }

    // 检查起始标志
    if(packet[0] != 0xAA)
    {
        return -2; // 起始标志错误
    }

    // 获取数据长度
    *data_length = packet[1];

    // 检查数据包总长度是否符合数据长度字段
    if(packet_length != 3 + *data_length)
    {
        return -3; // 数据包长度与数据长度字段不匹配
    }

    //计算校验和
    uint8_t calculated_checksum = calculate_checksum(packet, packet_length - 1);
    uint8_t received_checksum = packet[packet_length - 1];

    // 检查校验和
    if(calculated_checksum != received_checksum)
    {
        return -4; // 校验和错误
    }

    // 提取数据
    *data = &packet[2];

    return 0; // 解析成功
}



int main()
{
    SetConsoleOutputCP(65001);
    //    示例数据包
    uint8_t packet[] = {0xAA, 0x03, 0x11, 0x22, 0x33, 0xAA ^ 0x03 ^ 0x11 ^ 0x22 ^ 0x33};
    uint8_t packet_length = sizeof(packet);
    uint8_t *data;
    uint8_t data_length;

    // 解析协议
    int result = parse_protocol(packet, packet_length, &data, &data_length);

    if(result = 0)
    {
        printf("解析协议成功！\n");
        printf("数据长度： %d\n", data_length);
        printf("数据内容: ");
        for(uint8_t i = 0; i < data_length; i++)
        {
            printf("%02X ", data[i]);
        }
        printf("\n");
    } else {
        printf("协议解析失败， 错误码： %d\n", result);
    }

    return 0;
}